import { catalog } from "@mall/api-services"
import { PageHeader } from "antd"
import * as React from "react"
import { useState } from "react"
import { useHistory, useParams } from "react-router-dom"
import { messageError } from "../../utils/reason"

import classes from "./new-product.module.scss"
import ProductForm from "./product-form"

export default function NewProduct() {
  const history = useHistory()
  const { storeId = "" } = useParams()
  const [loading, setLoading] = useState(false)

  function onFinish(newProduct: catalog.Product) {
    setLoading(true)
    catalog.ProductServiceV1
      .createProduct(newProduct)
      .then(product => history.push(`/stores/${product.storeId}/products/${product.id}`))
      .catch(messageError)
      .finally(() => setLoading(false))
  }

  return (
    <div className={classes.newProduct}>
      <PageHeader title="发布商品" ghost={false}/>
      <div className={classes.newProductContent}>
        <ProductForm loading={loading}
                     product={catalog.Product.assign({ storeId })}
                     onFinish={onFinish}/>
      </div>
    </div>
  )
}
